<template lang="pug">
div
  FixedScroll
    div(slot="fixed")
      PageHeader(pageTitle="小票管理")

      ScanSearch(
          placeholder="小票单号"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )

      g-v.info(v-if="info")
        KvPair(v-if="info.BillNo" k="小票编号" :v="info.BillNo")
        KvPair(v-if="info.SStorgeCode" k="实体仓库" :v="info.SStorgeCode")
        KvPair(v-if="info.SWmNo" k="逻辑仓库" :v="info.SWmNo")
        KvPair(
            v-if="info.PartType != undefined"
            k="物料类型"
            :v="info.PartType | Enum('Receipt', 'PartType')"
            )
        KvPair(v-if="info.ApplyDept" k="申请部门" :v="info.ApplyDept")

    InputTable.table(
        slot="scroll"
        :headList="headList"
        :body="body"
        :isLoading="isLoading"
        @check-input="checkInput"
        @click-row="clickRow"
        )

    g-h.bottom-bar(slot="fixed-bottom" j-c="space-around" v-if="info")
      template(v-if="!pickButton.disabled")
        g-h.pick-group(a-i="center" v-if="pickType !== ''")
          div.pick-item(:class="{pickItemActive: pickType === '废品' }") 废品扫描
          div.pick-item(:class="{pickItemActive: pickType === '正品' }") 正品扫描
        Button(
            v-if="$root.User.permMap['SaveToPicking(小票管理_移动端)']"
            @click="pick"
            :text="pickButton.text"
            )
      template(v-else)
        Button(
            v-if="$root.User.permMap['SaveToOut(小票管理_移动端)']"
            @click="exportGoods"
            :text="exportButton.text"
            :disabled="exportButton.disabled"
            )
        Button(
            v-if="$root.User.permMap['SaveToFinish(小票管理_移动端)']"
            @click="save"
            :text="saveButton.text"
            :disabled="saveButton.disabled"
            )

</template>

<script>
import api from "$api"
import util from "$util"
import { mapState, mapGetters } from "vuex"

export default {
  data() {
    return {
      searchValue: "",
      isLoading: false,
      hasIllegalInput: false,

      clickableRow: {},

      loading: {
        search: false,
        pick: false,
        exportGoods: false,
        save: false,
      },

      pickButton: {
        text: "拣配",
        disabled: false,
      },
      exportButton: {
        text: "出库",
        disabled: true,
      },
      saveButton: {
        text: "完成",
        disabled: true,
      },

      headList: [
        { field: "PartNo", title: "物料号", checked: true },
        { field: "PartCname", title: "物料名称", checked: true },
        { field: "SupplierNum", title: "厂家号", checked: true },
        { field: "RequiredNum", title: "需求数量", checked: true },
        { field: "_realNum", title: "实际数量", checked: true },
        { field: "Num", title: "接/出数", checked: true },
      ],
    }
  },
  computed: {
    ...mapState({
      info: state => state.receipt.info,
      body: state => state.receipt.body,
      partnoAndList: state => state.receipt.partnoAndList,
      active: state => state.receipt.active,
      pickType: state => state.receipt.pickType,
    }),
  },
  watch: {
    active(v) {
      // 切换tab时要重新绑定手机上的扫描键
      if (v === "ScanPage") {
        this.registerScanner()
        this.$forceUpdate()
      }
    },
  },
  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }
      // 重置所有状态
      this.$store.commit("receipt/reset")

      this.isLoading = true
      this.loading.search = true
      try {
        let data = await api.ReceiptSearch({
          BillNo: value,
        })
        this.reset()
        this.$store.commit("receipt/setInfo", {
          info: data.BillHeadInfo,
        })

        let inputRowList = [] // 可以输入的行
        // 检查状态
        // 根据规则给库存设置默认值
        switch (data.BillHeadInfo.BillStatus) {
          case 0:
          case 4:
          case 5:
            let i = 0
            for (let item of data.BillDetailInfo) {
              if (item.IsBatch === 0) {
                util.Alert(`物料[${item.PartNo}]的管理模式未维护,请维护库位与物料关系后操作`)
                return
              }
              if (item.IsBatch === 1) {
                inputRowList.push(i)
              }
              i++
            }
            if (inputRowList.length < i) {
              for (let item of data.BillDetailInfo) {
                item._realNum = 0
              }
              for (let index of inputRowList) {
                data.BillDetailInfo[index]._realNum = data.BillDetailInfo[index].RequiredNum
              }
            } else {
              for (let item of data.BillDetailInfo) {
                item._realNum = item.RequiredNum
              }

              this.pickButton.disabled = false
            }
            break

          default:
            for (let item of data.BillDetailInfo) {
              item._realNum = item.RequiredNum
            }
        }

        let i = 0
        for (let item of data.BillDetailInfo) {
          if (item.IsBatch === 2) {
            this.clickableRow[i] = true // 可以点击的行
          }
          i++
        }

        // 给可点击的行设置样式
        let styleMap = new Array(data.BillDetailInfo.length)
        let firstField = this.headList[0].field
        for (let k in this.clickableRow) {
          styleMap[k] = {
            [firstField]: {
              color: "#1E88E5",
            }
          }
        }

        this.$store.commit("receipt/setBody", {
          body: {
            inputRowList,
            styleMap,
            list: data.BillDetailInfo,
          },
        })

        switch (data.BillHeadInfo.BillStatus) {
          case 0:
            if (data.BillHeadInfo.BillType === "103") {
              if (Object.keys(this.clickableRow).length > 0) {
                this.$store.commit("receipt/setPickType", {
                  pickType: "废品",
                })
              }
            }
            break
          case 1:
            this.pickButton.disabled = true
            this.pickButton.text = "已拣配"
            this.exportButton.disabled = false
            break
          case 2:
            this.pickButton.disabled = true
            this.pickButton.text = "已拣配"
            this.exportButton.text = "已出库"
            this.saveButton.disabled = false
            break
          case 3:
            this.pickButton.disabled = true
            this.pickButton.text = "已拣配"
            this.exportButton.text = "已出库"
            this.saveButton.text = "已完成"
            break
          case 4:
            this.$store.commit("receipt/setPickType", {
              pickType: "正品",
            })
            break
        }
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    // 拣配
    async pick() {
      if (this.loading.pick) {
        return
      }
      if (this.pickButton.disabled) {
        return
      }
      if (this.hasIllegalInput) {
        util.Alert("输入框中包含不合法的数据")
        return
      }

      for (let item of this.body.list) {
        if (item.RequiredNum !== parseInt(item._realNum)) {
          util.Alert(`物料号为${item.PartNo}的物料数量与实际数量不等`)
          return
        }
      }

      let operType = "Batch"
      if (Object.keys(this.clickableRow).length > 0) {
        operType = "StorageToPick"
        if (this.body.list[0].RequiredNum < 0) {
          operType = "RetiredToPick"
        }
      }

      let PickType = "NORMAL"
      switch (this.pickType) {
        case "废品":
          PickType = "XB"
          break
        case "正品":
          PickType = "RDC"
          break
      }
      
      // 筛选出合格的电池
      let barcodeDetailList = []
      for (let k in this.partnoAndList) {
        let list = this.partnoAndList[k].barcodeList
        let statusMap = this.partnoAndList[k].statusMap
        for (let item of list) {
          if (statusMap[item.BarcodeData] === util.STATUS_OK) {
            item.TranNo = this.info.BillNo
            barcodeDetailList.push(item)
          }
        }
      }

      this.loading.pick = true
      try {
        let data = await api.ReceiptPick({
          BillId: this.info.BillId,
          OperType: operType,
          PickType,
          barcodeDetailList,
        })

        if (this.pickType === "废品") {
          // 设置拣配类型
          this.$store.commit("receipt/setPickType", {
            pickType: "正品",
            clickableRow: this.clickableRow,
          })
        } else {
          this.pickButton.text = "已拣配"
          this.pickButton.disabled = true
          this.exportButton.disabled = false
        }

        // 清除电池缓存数据
        this.$store.commit("receipt/clearBatteryCache")
        this.info.BillStatus = 1
        this.$store.commit("receipt/setInfo", {
          info: this.info,
        })
        util.Toast("拣配成功")
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.pick = false
      }
    },

    // 出库
    async exportGoods() {
      if (this.loading.exportGoods) {
        return
      }
      if (this.exportButton.disabled) {
        return
      }

      this.loading.exportGoods = true
      try {
        let data = await api.ReceiptExport({
          BillId: this.info.BillId,
        })
        this.exportButton.text = "已出库"
        this.exportButton.disabled = true
        this.saveButton.disabled = false
        util.Toast("出库成功")
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.exportGoods = false
      }
    },

    async save() {
      if (this.loading.save) {
        return
      }
      if (this.saveButton.disabled) {
        return
      }

      let operType = "Batch"
      for (let item of this.body.list) {
        if (item.IsBatch === 2) {
          operType = "StorageToOut"
          if (item.RequiredNum < 0) {
            operType = "Retired"
          }
          break
        }
      }

      this.loading.save = true
      util.Indicator.open()
      try {
        await api.ReceiptSave({
          BillId: this.info.BillId,
          BillNo: this.info.BillNo,
          OperType: operType,
        })
        this.saveButton.text = "已完成"
        this.saveButton.disabled = true
        // 清除电池缓存数据
        this.$store.commit("receipt/clearBatteryCache")
        util.Indicator.close()
        util.Toast("完成成功")
      } catch(err) {
        util.Indicator.close()
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.save = false
      }
    },

    // 重置本页的状态
    reset() {
      this.pickButton = {
        text: "拣配",
        disabled: false,
      }
      this.exportButton = {
        text: "出库",
        disabled: true,
      }
      this.saveButton = {
        text: "完成",
        disabled: true,
      }
    },

    // 检查输入数据
    checkInput(v) {
      if (v == null || v === "") {
        return
      }
      let isNatural = /^(0|[1-9]\d*)$/.test(v)
      if (!isNatural) {
        this.hasIllegalInput = true
        util.Toast(`错误的输入: ${v}`)
      } else if (this.hasIllegalInput) {
        this.hasIllegalInput = false
      }
    },

    // 点击行转到扫电池页面
    clickRow(row, index) {
      if (this.clickableRow[index]) {
        this.$store.commit("receipt/switchToBarcode", {
          index,
        })
      }
    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },
  },

  created() {
    this.registerScanner()
  },
}
</script>

<style lang="stylus" scoped>

.info
  border: 1px solid grey200

.table
  scan-table()

.bottom-bar
  bottom-bar()

.pick-item
  padding: 0.3rem
  margin-right: 0.5rem
  color: grey500

.pickItemActive
  color: black
  background: green300

</style>
